package com.superhero.website.security;

import com.superhero.common.pojo.entity.AuthUser;
import com.superhero.common.repository.AuthUserRepository;
import com.superhero.common.utils.OptionalUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class CustomUserService implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(CustomUserService.class);
    @Resource
    AuthUserRepository userRepository;

    /**
     * 通过用户名从数据库中读取该用户账户信息及权限信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public JwtAuthUser loadUserByUsername(String username) throws UsernameNotFoundException {
        AuthUser user = OptionalUtil.get(userRepository.findAuthUserByUsername(username));
        logger.info("加载用户: {}", user.getUsername());
        return new JwtAuthUser(user);
    }

}
